"""
工具函数模块 - 用于定义聊天机器人可以使用的各种工具
"""

import json
from datetime import datetime

# 定义工具函数
def get_current_time():
    """获取当前时间"""
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return {"time": current_time}

def calculate(expression):
    """计算简单的数学表达式"""
    try:
        result = eval(expression)
        return {"result": result}
    except Exception as e:
        return {"error": str(e)}

# 前端工具占位函数
def frontend_tool_handler(**kwargs):
    """前端工具处理函数，实际执行在前端"""
    # 这个函数不会被实际调用，只是一个占位符
    # 前端工具调用会被转发到前端执行
    return {"message": "此工具在前端执行"}

# 定义可用工具列表
available_tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "获取当前时间",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "计算数学表达式",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "要计算的数学表达式，如'2+2'或'10*5'"
                    }
                },
                "required": ["expression"]
            }
        }
    }
]

# 工具函数映射
tool_functions = {
    "get_current_time": get_current_time,
    "calculate": calculate
} 

def get_tool_info():
    """
    获取工具信息，用于前端展示
    
    Returns:
        list: 包含工具名称、描述、参数信息的字典列表
    """
    tool_info = []
    for tool in available_tools:
        if tool["type"] == "function":
            func_info = tool["function"]
            tool_info.append({
                "name": func_info["name"],
                "description": func_info["description"],
                "parameters": func_info["parameters"],
                "type": "function"
            })
    return tool_info

def register_frontend_tool(tool_id, name, description, parameters):
    """
    注册前端工具到可用工具列表
    
    Args:
        tool_id: 工具唯一ID
        name: 工具名称
        description: 工具描述
        parameters: 工具参数定义
    """
    # 创建工具定义
    tool_def = {
        "type": "function",
        "function": {
            "name": tool_id,
            "description": f"{name}: {description} (前端工具)",
            "parameters": parameters
        }
    }
    
    # 添加到可用工具列表
    available_tools.append(tool_def)
    
    # 添加到工具函数映射
    tool_functions[tool_id] = frontend_tool_handler 